﻿#include "xioplugbase.h"

XIOPlugBase::XIOPlugBase(QObject* parent ):
QObject(parent){

	qDebug() << "IO 构造";
	_Rdata.reset(new QQueue<IOStream>);
	_Tdata.reset(new QQueue<IOStream>);
	clearBuffer();
}

XIOPlugBase::~XIOPlugBase()
{
	_Rmutex.tryLock(1);
	_Rmutex.unlock();
	_Tmutex.tryLock(1);
	_Tmutex.unlock();
}

void XIOPlugBase::clearBuffer()
{
	_Rmutex.lock();
	_Rdata->clear();
	_Rmutex.unlock();
	_Tmutex.lock();
	_Tdata->clear();
	_Tmutex.unlock();
	Rnum = Tnum = Enum = 0;
	RdataSize = TdataSize = EdataSize = 0;
}

QList<XIOPlugBase::IOStream> XIOPlugBase::readAll()
{

	_Rmutex.lock();
	QList< IOStream> _R(*_Rdata);
	_Rdata->clear();
	_Rmutex.unlock();
	return _R;
}

QList<XIOPlugBase::IOStream> XIOPlugBase::read(const int num)
{
	int count = 0;
	_Rmutex.lock();
	QList<XIOPlugBase::IOStream> ret;
	if(num>= _Rdata->size()) ret = *_Rdata;
	while (count != num)
	{
		ret.append(_Rdata->dequeue());
	}
	_Rmutex.unlock();
	return ret;
}

void XIOPlugBase::Asyn_write(IOStream data)
{
	
		_Tmutex.lock();
		_Tdata->enqueue(data);
		_Tmutex.unlock();
		QMetaObject::invokeMethod(this, "_runAPP",
			Qt::AutoConnection);
}

void XIOPlugBase::Asyn_write(QList<IOStream> datas)
{
	_Tmutex.lock();
	for (auto data : datas) {
		_Tdata->enqueue(data);
	}
	_Tmutex.unlock();
	QMetaObject::invokeMethod(this, "_runAPP",
		Qt::AutoConnection);
}

void XIOPlugBase::setchannels( QString channel, bool add)
{
	qDebug() << channel;
	if (add)
	{
		if (!_channels.contains(channel))
			_channels.append(channel);
	}
	else _channels.removeAll(channel);
	emit channelChanged(channel);
}
